<template>
    <div class="number-compare-input">
        <a-select v-model:value="compareValue.type">
            <a-select-option v-for="(optionText, optionValue) in optionList" :key="optionValue" :value="optionValue">
                {{ optionText }}
            </a-select-option>
        </a-select>
        <a-input-number v-if="compareValue.type === 'FIXED'" v-model:value="compareValue.value" class="value-input" />
    </div>
</template>

<script lang="ts">
    import { defineComponent, ref, watch } from 'vue'
    import { useI18n } from 'vue-i18n'

    export default defineComponent({
        props: {
            value: {
                type: Object,
                default: () => ({})
            }
        },
        setup(props) {
            const { t } = useI18n()

            const optionList = {
                FIXED: t('fixedValue'),
                AVERAGE: t('avgValue')
            }

            const compareValue = ref()

            watch(
                () => props.value,
                () => {
                    if (compareValue.value !== props.value) {
                        compareValue.value = props.value
                    }
                },
                {
                    immediate: true
                }
            )

            // 暴露给外部组件，用于验证
            function validate() {
                if (
                    compareValue.value.type === 'FIXED' &&
                    !compareValue.value.value &&
                    compareValue.value.value !== 0
                ) {
                    return Promise.reject(t('fixedValueRequired'))
                }
                return Promise.resolve(true)
            }

            return {
                optionList,
                compareValue,

                validate
            }
        }
    })
</script>

<style lang="less" scoped>
    .number-compare-input {
        display: flex;

        .value-input {
            margin-left: 10px;
            flex-grow: 1;
        }
    }
</style>

<i18n>
zh-CN:
  fixedValue: '固定值'
  avgValue: '平均值'
  fixedValueRequired: '请输入固定值'
</i18n>
